package cn.iocoder.boot.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.iocoder.boot.dto.QueryTO;
import cn.iocoder.boot.entity.ComponentPrice;
import cn.iocoder.boot.entity.ComponentStock;
import cn.iocoder.boot.entity.ComponentSupplier;
import cn.iocoder.boot.enums.SupplierCodeEnum;
import cn.iocoder.boot.mapper.ComponentPriceMapper;
import cn.iocoder.boot.mapper.ComponentStockMapper;
import cn.iocoder.boot.mapper.ComponentSupplierMapper;
import cn.iocoder.boot.service.ComponentStockService;
import cn.iocoder.boot.service.QuoteService;
import cn.iocoder.boot.service.impl.supplier.*;
import cn.iocoder.boot.utils.MessageUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import com.baomidou.lock.annotation.Lock4j;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.internal.StringUtil;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collectors;


@Service
@Slf4j
public class QuoteServiceImpl implements QuoteService {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(QuoteService.class);
    @Autowired
    private ComponentStockMapper stockMapper;

    @Autowired
    private ComponentPriceMapper priceMapper;

    @Autowired
    private DigikeyServiceImpl digikeyServiceImpl;

    @Autowired
    private ICEasyServiceImpl iCEasyService;

    @Autowired
    private ComponentPriceServiceImpl priceService;
    @Resource
    private ComponentStockService componentStockService;

    @Resource
    private ComponentSupplierMapper componentSupplierMapper;

    @Autowired
    private ElementServiceImpl elementService;
    @Autowired
    private JBCHIPServiceImpl jbchipService;

    @Autowired
    private MouserServiceImpl mouserService;

    @Autowired
    private YunhanServiceImpl yunhanService;

    @Autowired
    private SHTServiceImpl shtServiceImpl;

    @Autowired
    private TMEServiceImpl tmeServiceImpl;

    @Resource(name = "quoteExecutor")
    private ThreadPoolExecutor quoteExecutor;

    @Override
    @Lock4j(keys = {"#to.model"}, expire = 60000, acquireTimeout = 60000)
    public Page<ComponentStock> query(QueryTO to) throws Exception {
        // 处理空查询条件，直接返回空页
        if (to == null) {
            return new Page<ComponentStock>(0, 0, 0).setRecords(Collections.emptyList());
        }

        // 默认人民币币种
        String currency = StringUtil.isBlank(to.getCurrency()) ? "RMB" : to.getCurrency();
        to.setCurrency(currency);

        LambdaQueryWrapper<ComponentStock> queryWrapper = new LambdaQueryWrapper<>();

        // 处理型号查询条件
        if (StringUtil.isBlank(to.getModel())) {
            // 型号为空时，筛选有生效价格的库存
            LambdaQueryWrapper<ComponentPrice> priceWrapper = new LambdaQueryWrapper<>();
            priceWrapper.eq(ComponentPrice::getCurrency, currency);
            List<ComponentPrice> componentPrices = priceMapper.selectList(priceWrapper);

            // 没有符合条件的价格记录，返回空页
            if (CollectionUtil.isEmpty(componentPrices)) {
                return new Page<ComponentStock>(to.getPageNo(), to.getPageSize(), 0).setRecords(Collections.emptyList());
            }

            // 提取库存ID列表并设置查询条件
            List<String> stockIds = componentPrices.stream()
                    .map(ComponentPrice::getUniqueId)
                    .collect(Collectors.toList());
            queryWrapper.in(ComponentStock::getUniqueId, stockIds);
        } else {
            // 型号不为空时处理：去除首尾空格
            to.setModel(StrUtil.trim(to.getModel()));

            // 库存类型为1且供应商为空时，默认取优先级前三的供应商
            if (Objects.equals(to.getStockType(), 1) && StringUtil.isBlank(to.getSupplier())) {
                to.setSupplier(componentSupplierMapper.findPriorityMin3Nos());
            }

            // 型号或关键词匹配
            queryWrapper.and(wrapper -> wrapper
                    .eq(ComponentStock::getModel, to.getModel())
                    .or()
                    .eq(ComponentStock::getKeyword, to.getModel())
            );
        }

        // 通用筛选条件
        if (to.getStockType() != null) {
            queryWrapper.eq(ComponentStock::getStockType, to.getStockType());
        }
        if (!StringUtil.isBlank(to.getSupplier())) {
            queryWrapper.in(ComponentStock::getSupplierCode, Arrays.asList(to.getSupplier().split(",")));
        }

        // 排序条件
        queryWrapper.orderByAsc(ComponentStock::getId);

        // 执行分页查询
        Page<ComponentStock> page = new Page<>(to.getPageNo(), to.getPageSize());
        Page<ComponentStock> componentStockIPage = stockMapper.selectPage(page, queryWrapper);
        List<ComponentStock> records = componentStockIPage.getRecords();

        // 处理库存类型为1的特殊逻辑
        if (Objects.equals(to.getStockType(), 1)) {
            // 补充缺失的供应商数据（当型号不为空时）
            if (!StringUtil.isBlank(to.getModel())) {
                supplementMissingSupplierData(to, records);
                // 重新查询以获取补充后的数据
                componentStockIPage = stockMapper.selectPage(page, queryWrapper);
                records = componentStockIPage.getRecords();
            }

            // 处理价格数据
            if (!records.isEmpty()) {
                processPriceDataByQuote(to, records);

                // 查询并设置价格列表（合并重复查询逻辑）
                List<String> ids = records.stream()
                        .map(ComponentStock::getUniqueId)
                        .collect(Collectors.toList());

                CommonResult<List<ComponentPrice>> priceResult = priceService.listComponentPricesForTime(ids, currency);
                if (priceResult.getData() != null && !priceResult.getData().isEmpty()) {
                    Map<String, List<ComponentPrice>> priceMap = priceResult.getData().stream()
                            .filter(price -> price.getUniqueId() != null)
                            .collect(Collectors.groupingBy(ComponentPrice::getUniqueId));

                    records.forEach(stock -> {
                        List<ComponentPrice> componentPrices = priceMap.get(stock.getUniqueId());
                        if (CollectionUtil.isEmpty(componentPrices)) {
                            ComponentPrice componentPrice = new ComponentPrice();
                            componentPrice.setJson("价格已过期，请输入详细型号获取");
                            componentPrice.setCostJson("价格已过期，请输入详细型号获取");
                            componentPrice.setSaleJson("价格已过期，请输入详细型号获取");
                            List<ComponentPrice> defaultList = new ArrayList<>();
                            defaultList.add(componentPrice);
                            stock.setPriceList(defaultList);
                        } else {
                            stock.setPriceList(componentPrices);
                        }

                    });
                }
                componentStockIPage.setRecords(records);
            }
        } else {
            // 非库存类型1的价格处理
            if (!records.isEmpty()) {
                List<String> ids = records.stream()
                        .map(ComponentStock::getUniqueId)
                        .collect(Collectors.toList());

                CommonResult<List<ComponentPrice>> priceResult = priceService.listComponentPricesForTime(ids, currency);
                if (priceResult.getData() != null && !priceResult.getData().isEmpty()) {
                    Map<String, List<ComponentPrice>> priceMap = priceResult.getData().stream()
                            .filter(price -> price.getUniqueId() != null)
                            .collect(Collectors.groupingBy(ComponentPrice::getUniqueId));

                    records.forEach(stock -> {
                        List<ComponentPrice> componentPrices = priceMap.get(stock.getUniqueId());
                        if (CollectionUtil.isEmpty(componentPrices)) {
                            ComponentPrice componentPrice = new ComponentPrice();
                            componentPrice.setJson("价格已过期，请输入详细型号获取");
                            componentPrice.setCostJson("价格已过期，请输入详细型号获取");
                            componentPrice.setSaleJson("价格已过期，请输入详细型号获取");
                            List<ComponentPrice> defaultList = new ArrayList<>();
                            defaultList.add(componentPrice);
                            stock.setPriceList(defaultList);
                        } else {
                            stock.setPriceList(componentPrices);
                        }
                    });
                }
                componentStockIPage.setRecords(records);
            }
        }

        return componentStockIPage;
    }

    /**
     * 查询配置
     *
     * @param to
     * @return
     */
    private Map<String, BigDecimal> getComponentSupplierMap(QueryTO to) {
        List<ComponentSupplier> componentSupplierList = new ArrayList<>();
        if (!StringUtil.isBlank(to.getSupplier())) {
            componentSupplierList = componentSupplierMapper.selectList(null);
        } else {
            String[] suppliers = to.getSupplier().split(",");
            componentSupplierList = componentSupplierMapper.selectList(Wrappers.<ComponentSupplier>lambdaQuery()
                    .in(ComponentSupplier::getNo, Arrays.asList(suppliers)));
        }
        // 对值进行null判断，如果为null则使用BigDecimal.valueOf(2)
        // 遇到重复key时保留后面的值
        return componentSupplierList.stream()
                .collect(Collectors.toMap(
                        ComponentSupplier::getNo,
                        // 对值进行null判断，如果为null则使用BigDecimal.valueOf(2)
                        cs -> cs.getExpireDate() != null ? cs.getExpireDate() : BigDecimal.valueOf(2),
                        (v1, v2) -> v2 // 遇到重复key时保留后面的值
                ));
    }


    @Override
    public IPage<ComponentStock> queryBaseInfo(QueryTO to) {
        LambdaQueryWrapper<ComponentStock> queryWrapper = new LambdaQueryWrapper<>();
        if (!StringUtil.isBlank(to.getModel())) {
            queryWrapper.eq(ComponentStock::getModel, to.getModel());
        }
        IPage<ComponentStock> page = new Page<>(to.getPageNo(), to.getPageSize());
        return stockMapper.selectPage(page, queryWrapper);
    }

    @Override
    public List<ComponentPrice> queryList(QueryTO to) throws Exception {
        return null;
    }

    /**
     * 查找匹配的数量，逻辑与findPriceForQuantity相同
     * 找到小于等于目标数量的最大库存数量
     */
    public static Long findQuantityForQuantity(JSONArray jsonArray, Long quantity) {
        Long resultQuantity = null;
        Long maxQuantity = -1L; // 用来存储小于给定库存量的最大值

        // 遍历所有库存项，找到小于给定库存量的最大库存
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            Long stockQuantity = obj.getLong("Quantity");

            // 如果库存量小于等于给定数量，且是最大的匹配
            if (stockQuantity <= quantity && stockQuantity > maxQuantity) {
                maxQuantity = stockQuantity;
                resultQuantity = stockQuantity; // 这里直接存储数量而非价格
            }
        }

        return resultQuantity;
    }

    public static String findPriceForQuantity(JSONArray jsonArray, Long quantity) {
        String resultPrice = null;
        Long maxQuantity = -1L; // 用来存储小于给定库存量的最大值

        // 遍历所有库存项，找到小于给定库存量的最大库存
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            Long stockQuantity = obj.getLong("Quantity");
            String price = obj.getStr("Price");

            // 如果库存量小于等于给定数量，且是最大的匹配
            if (stockQuantity <= quantity && stockQuantity > maxQuantity) {
                maxQuantity = stockQuantity;
                resultPrice = price;
            }
        }

        return resultPrice;
    }

    public static String findPriceForMaxQuantity(JSONArray jsonArray) {
        String maxPrice = null;
        Long maxQuantity = -1L; // 用来存储最大的库存量

        // 遍历所有库存项，找到最大的库存及其对应的价格
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            Long stockQuantity = obj.getLong("Quantity");
            String price = obj.getStr("Price");

            // 如果当前库存量大于已记录的最大库存量，则更新
            if (stockQuantity > maxQuantity) {
                maxQuantity = stockQuantity;
                maxPrice = price;
            }
        }

        return maxPrice;
    }

    public static String findPriceForQuantityOfDigikey(JSONArray jsonArray, Long quantity, String currency, Long num) {
        String resultPrice = null;
        Long maxQuantity = -1L; // 用来存储小于给定库存量的最大值

        // 遍历所有库存项，找到小于给定库存量的最大库存
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            Long stockQuantity = obj.getLong("Quantity");
            String price = obj.getStr("Price");

            // 如果库存量小于等于给定数量，且是最大的匹配
            if (stockQuantity <= quantity && stockQuantity > maxQuantity) {
                maxQuantity = stockQuantity;
                resultPrice = price;
            }
        }
        // 计算额外值
        BigDecimal additionalValue = Objects.equals(currency, "RMB")
                ? BigDecimal.valueOf(49.0).divide(BigDecimal.valueOf(num), 4, BigDecimal.ROUND_HALF_UP)
                : BigDecimal.valueOf(7.0).divide(BigDecimal.valueOf(num), 4, BigDecimal.ROUND_HALF_UP);
        if (resultPrice != null) {
            return new BigDecimal(resultPrice).add(additionalValue).toString();
        }
        return resultPrice;
    }


    @Override
    @Lock4j(keys = {"#to.model"}, expire = 60000, acquireTimeout = 60000)
    public List<ComponentPrice> queryListOfRemote(QueryTO to) throws Exception {
        // 1. 参数校验与默认值设置
        if (!validateAndSetDefaultParams(to)) {
            return new ArrayList<>();
        }

        // 收集所有结果并汇总
        List<CompletableFuture<List<ComponentPrice>>> futures = new ArrayList<>();
        Map<String, BigDecimal> componentSupplierMap = getComponentSupplierMap(to);

        for (String supplierCode : to.getSupplier().split(",")) {
            SupplierCodeEnum supplier = SupplierCodeEnum.fromCode(supplierCode);
            CompletableFuture<List<ComponentPrice>> future = createSupplierQueryOneFuture(supplier, to, componentSupplierMap);
            futures.add(future);
        }

        if (CollectionUtil.isNotEmpty(futures)) {
            // 等待所有异步任务完成
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

            // 汇总所有结果
            List<ComponentPrice> allResults = new ArrayList<>();
            for (CompletableFuture<List<ComponentPrice>> future : futures) {
                List<ComponentPrice> componentPrices = future.get();
                if (!CollectionUtil.isEmpty(componentPrices)) {
                    allResults.addAll(componentPrices);
                }
            }
            assembleResultList(to, allResults);

            // 7. 按供应商分组（保持原逻辑）
            return groupBySupplierCode(allResults, Arrays.asList(to.getSupplier().split(",")));
        }
        return new ArrayList<>();
    }

    // ========================== 私有工具方法 ==========================

    /**
     * 参数校验与默认值设置
     *
     * @param to 查询参数
     * @return 校验结果：true=通过，false=不通过（需返回空列表）
     */
    private boolean validateAndSetDefaultParams(QueryTO to) {
        // 基础参数校验
        if (to == null) {
            return false;
        }

        // StockType=1时必须有型号
        if (to.getStockType() == 1 && StrUtil.isBlank(to.getModel())) {
            return false;
        }

        // 设置默认货币
        if (StrUtil.isBlank(to.getCurrency())) {
            to.setCurrency("RMB");
        }

        // StockType=1且无供应商时设置默认供应商
        if (to.getStockType() == 1 && StrUtil.isBlank(to.getSupplier())) {
            to.setSupplier("VEND0004,VEND0005,VEND0006,VEND0007,VEND0008");
        }

        // 去除型号前后空格
        to.setModel(StrUtil.strip(to.getModel(), " "));

        return true;
    }

    /**
     * 构建库存查询条件
     *
     * @param to 查询参数
     * @return LambdaQueryWrapper
     */
    private LambdaQueryWrapper<ComponentStock> buildQueryWrapper(QueryTO to) {
        LambdaQueryWrapper<ComponentStock> queryWrapper = new LambdaQueryWrapper<>();

        // 型号检索（精确匹配型号或关键词）
        if (StrUtil.isNotBlank(to.getModel())) {
            queryWrapper.and(wrapper -> wrapper
                    .eq(ComponentStock::getModel, to.getModel())
                    .or()
                    .eq(ComponentStock::getKeyword, to.getModel())
            );
        }

        // 库存类型检索
        if (to.getStockType() != null) {
            queryWrapper.eq(ComponentStock::getStockType, to.getStockType());
        }

        // 供应商检索（多供应商IN查询）
        if (StrUtil.isNotBlank(to.getSupplier())) {
            List<String> suppliers = Arrays.asList(to.getSupplier().split(","));
            queryWrapper.in(ComponentStock::getSupplierCode, suppliers);
        }

        return queryWrapper;
    }

    /**
     * 补充缺失的供应商数据（异步调用各供应商服务）
     *
     * @param to          查询参数
     * @param recordsList 已查询到的库存列表
     */
    private void supplementMissingSupplierData(QueryTO to, List<ComponentStock> recordsList) {
        // 1. 获取目标供应商集合与已存在供应商集合
        Set<String> targetSuppliers = new HashSet<>(Arrays.asList(to.getSupplier().split(",")));
        Set<String> existingSuppliers = recordsList.stream()
                .map(ComponentStock::getSupplierCode)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.toSet());

        // 2. 计算缺失的供应商
        List<String> missingSuppliers = targetSuppliers.stream()
                .filter(supplier -> !existingSuppliers.contains(supplier))
                .collect(Collectors.toList());

        if (CollectionUtil.isEmpty(missingSuppliers)) {
            return;
        }

        // 3. 构建组件供应商映射
        Map<String, BigDecimal> componentSupplierMap = getComponentSupplierMap(to);

        // 4. 创建异步任务
        List<CompletableFuture<List<ComponentPrice>>> futures = new ArrayList<>();
        for (String supplierCode : missingSuppliers) {
            SupplierCodeEnum supplier = SupplierCodeEnum.fromCode(supplierCode);

            // 根据供应商类型创建异步任务
            CompletableFuture<List<ComponentPrice>> future = createSupplierQueryOneFuture(supplier, to, componentSupplierMap);
            if (future != null) {
                futures.add(future);
            }
        }

        // 5. 等待所有异步任务完成
        if (CollectionUtil.isNotEmpty(futures)) {
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        }
    }

    /**
     * 创建供应商queryOne异步任务
     *
     * @param supplier             供应商枚举
     * @param to                   查询参数
     * @param componentSupplierMap 组件供应商映射
     * @return 异步任务
     */
    private CompletableFuture<List<ComponentPrice>> createSupplierQueryOneFuture(SupplierCodeEnum supplier,
                                                                                 QueryTO to,
                                                                                 Map<String, BigDecimal> componentSupplierMap) {
        try {
            return switch (supplier) {
                case JBCHIP -> createAsyncTaskResult(() -> jbchipService.queryOne(to.getModel(), componentSupplierMap),
                        "京北通宇商城", Collections.singletonList(to.getModel()));
                case MOUSER -> createAsyncTaskResult(() -> mouserService.queryOne(to.getModel(), componentSupplierMap),
                        "昴氏", Collections.singletonList(to.getModel()));
                case ELEMENT ->
                        createAsyncTaskResult(() -> elementService.queryOne(to.getModel(), componentSupplierMap),
                                "易络盟", Collections.singletonList(to.getModel()));
                case IC ->
                        createAsyncTaskResult(() -> yunhanService.queryOne(to.getModel(), to.getCurrency(), componentSupplierMap),
                                "云汉", Collections.singletonList(to.getModel()));
                case SHT ->
                        createAsyncTaskResult(() -> shtServiceImpl.queryOne(to.getModel(), to.getCurrency(), componentSupplierMap),
                                "圣禾堂", Collections.singletonList(to.getModel()));
                case DIGIKEY ->
                        createAsyncTaskResult(() -> digikeyServiceImpl.queryOne(to.getModel(), to.getCurrency(), componentSupplierMap),
                                "得捷", Collections.singletonList(to.getModel()));
                case TME ->
                        createAsyncTaskResult(() -> tmeServiceImpl.queryOne(to.getModel(), to.getCurrency(), componentSupplierMap),
                                "TME", Collections.singletonList(to.getModel()));
                case ICEAZY -> createAsyncTaskResult(() -> iCEasyService.queryOne(to.getModel(), componentSupplierMap),
                        "中电港", Collections.singletonList(to.getModel()));
                default -> {
                    logger.warn("不支持的供应商类型：{}", supplier);
                    yield CompletableFuture.completedFuture(Collections.emptyList());
                }
            };
        } catch (Exception e) {
            logger.error("创建供应商[{}]queryOne任务失败", supplier.getCode(), e);
            return CompletableFuture.completedFuture(Collections.emptyList());
        }
    }


    private void processPriceDataByQuote(QueryTO to, List<ComponentStock> recordsList) {
        // 1. 校验库存数据
        if (CollectionUtil.isEmpty(recordsList)) {
            return;
        }

        // 2. 获取库存ID列表
        List<String> stockIds = recordsList.stream()
                .map(ComponentStock::getUniqueId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());

        // 3. 初始查询价格
        Map<String, ComponentPrice> priceMap = getComponentPriceMap(stockIds, to.getCurrency());

        // 4. 筛选缺失价格的库存记录
        List<ComponentStock> missingPriceRecords = recordsList.stream()
                .filter(record -> !priceMap.containsKey(record.getUniqueId()))
                .collect(Collectors.toList());
        if (CollectionUtil.isNotEmpty(missingPriceRecords)) {
            supplementMissingPriceData(to, recordsList, missingPriceRecords);
        }
    }

    /**
     * 获取组件价格映射（StockId -> ComponentPrice）
     *
     * @param stockIds 库存ID列表
     * @param currency 货币类型
     * @return 价格映射
     */
    private Map<String, ComponentPrice> getComponentPriceMap(List<String> stockIds, String currency) {
        if (CollectionUtil.isEmpty(stockIds)) {
            return Collections.emptyMap();
        }

        CommonResult<List<ComponentPrice>> priceResult = priceService.listComponentPricesForTime(stockIds, currency);
        if (priceResult == null || CollectionUtil.isEmpty(priceResult.getData())) {
            return Collections.emptyMap();
        }

        // 重复key时保留后者（根据原逻辑）
        return priceResult.getData().stream()
                .collect(Collectors.toMap(
                        ComponentPrice::getUniqueId,
                        Function.identity(),
                        (existing, replacement) -> replacement
                ));
    }

    /**
     * 补充缺失的价格数据（异步调用各供应商服务）
     *
     * @param to                  查询参数
     * @param allStockRecords     所有库存记录
     * @param missingPriceRecords 缺失价格的库存记录
     */
    private void supplementMissingPriceData(QueryTO to, List<ComponentStock> allStockRecords, List<ComponentStock> missingPriceRecords) {
        // 1. 分类缺失价格的库存记录（按供应商）
        Map<SupplierCodeEnum, List<Long>> supplierStockIdMap = classifyMissingPriceRecords(missingPriceRecords);

        if (supplierStockIdMap.isEmpty()) {
            return;
        }

        // 2. 准备通用数据
        List<String> models = getDistinctModels(allStockRecords);
        Map<String, BigDecimal> componentSupplierMap = getComponentSupplierMap(to);

        // 3. 创建异步价格查询任务
        List<CompletableFuture<Void>> futures = new ArrayList<>();
        for (Map.Entry<SupplierCodeEnum, List<Long>> entry : supplierStockIdMap.entrySet()) {
            SupplierCodeEnum supplier = entry.getKey();
            if (CollectionUtil.isEmpty(entry.getValue())) {
                continue;
            }
            CompletableFuture<Void> future = createSupplierQueryPriceFuture(
                    supplier, to, models, componentSupplierMap, allStockRecords);
            if (future != null) {
                futures.add(future);
            }
        }

        // 4. 等待所有异步任务完成
        if (CollectionUtil.isNotEmpty(futures)) {
            CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        }
    }

    /**
     * 分类缺失价格的库存记录（按供应商）
     *
     * @param missingPriceRecords 缺失价格的库存记录
     * @return 供应商->库存ID列表映射
     */
    private Map<SupplierCodeEnum, List<Long>> classifyMissingPriceRecords(List<ComponentStock> missingPriceRecords) {
        Map<SupplierCodeEnum, List<Long>> resultMap = new EnumMap<>(SupplierCodeEnum.class);

        for (ComponentStock record : missingPriceRecords) {
            String supplierCode = record.getSupplierCode();
            if (StrUtil.isBlank(supplierCode)) {
                logger.info("库存记录[{}]无供应商编码，跳过价格补充", record);
                continue;
            }

            SupplierCodeEnum supplier = SupplierCodeEnum.fromCode(supplierCode);

            // 按供应商分组添加库存ID
            resultMap.computeIfAbsent(supplier, k -> new ArrayList<>())
                    .add(record.getId());
        }

        return resultMap;
    }

    /**
     * 获取去重的型号列表
     *
     * @param stockRecords 库存记录列表
     * @return 去重型号列表
     */
    private List<String> getDistinctModels(List<ComponentStock> stockRecords) {
        return stockRecords.stream()
                .filter(stock -> StrUtil.isNotBlank(stock.getKeyword()))
                .collect(Collectors.toMap(
                        ComponentStock::getKeyword,
                        ComponentStock::getModel,
                        (existing, replacement) -> existing
                ))
                .values().stream()
                .distinct()
                .collect(Collectors.toList());
    }

    /**
     * 构建ID映射（用于价格查询）
     *
     * @param stockRecords 库存记录
     * @param keyGenerator 键生成器
     * @return ID映射
     */
    private Map<String, Long> buildIdsResult(List<ComponentStock> stockRecords,
                                             Function<ComponentStock, String> keyGenerator, String supplierCode) {
        return stockRecords.stream()
                .filter(stock -> Objects.equals(stock.getSupplierCode(), supplierCode))
                .collect(Collectors.toMap(
                        keyGenerator,
                        ComponentStock::getId,
                        (existing, replacement) -> existing
                ));
    }

    /**
     * 创建供应商价格查询异步任务
     */
    private CompletableFuture<Void> createSupplierQueryPriceFuture(SupplierCodeEnum supplier,
                                                                   QueryTO to,
                                                                   List<String> models,
                                                                   Map<String, BigDecimal> componentSupplierMap,
                                                                   List<ComponentStock> allStockRecords) {
        try {
            return switch (supplier) {
                case MOUSER -> createAsyncTask(() -> mouserService.query(models, componentSupplierMap),
                        "昴氏", models);
                case ELEMENT -> createAsyncTask(() -> elementService.query(models, componentSupplierMap),
                        "易络盟", models);
                case IC -> createAsyncTask(() -> yunhanService.query(models, to.getCurrency(), componentSupplierMap),
                        "云汉", models);
                case SHT -> createAsyncTask(() -> shtServiceImpl.query(models, to.getCurrency(), componentSupplierMap),
                        "圣禾堂", models);
                case DIGIKEY ->
                        createAsyncTask(() -> digikeyServiceImpl.query(allStockRecords, to.getCurrency(), componentSupplierMap),
                                "得捷", models);
                case TME ->
                        createAsyncTask(() -> tmeServiceImpl.query(allStockRecords, to.getCurrency(), componentSupplierMap),

                                "TME", models);
                case ICEAZY ->
                        createAsyncTask(() -> iCEasyService.query(models, componentSupplierMap), "中电港", models);
                default -> {
                    logger.warn("不支持的供应商价格查询：{}", supplier);
                    yield null;
                }
            };
        } catch (Exception e) {
            logger.error("创建供应商[{}]价格查询任务失败", supplier.getCode(), e);
            return null;
        }
    }


    private void assembleResultList(QueryTO to, List<ComponentPrice> componentPriceList) {
        List<ComponentPrice> resultList = new ArrayList<>();
        Long num = to.getNum();

        for (ComponentPrice price : componentPriceList) {
            ComponentStock stock = price.getStockInfo();
            Long matchNum;
            boolean flag = false;

            // 判断供应商是否为VEND0005
            if (stock != null && "VEND0005".equals(stock.getSupplierCode())) {
                String encapsulation = price.getEncapsulation();
                boolean hasTRorTB = encapsulation != null && (encapsulation.contains("TR") || encapsulation.contains("TB"));

                if (hasTRorTB) {
                    // 包装包含TR或TB时，取num和price.stock中的较小值
                    Long numVal = Objects.isNull(num) ? 0L : num;
                    Long stockNum = price.getStock() != null ? price.getStock() : 0L;
                    matchNum = Math.min(numVal, stockNum);
                    price.setQty(matchNum.intValue());
                    flag = true;
                } else {
                    // 包装不包含TR或TB时，查找同型号包含TR/TB包装的记录
                    String currentModel = stock.getModel();
                    Integer trTbQty = null;

                    if (currentModel != null) {
                        // 遍历列表查找相同model且包装包含TR/TB的价格记录
                        for (ComponentPrice otherPrice : componentPriceList) {
                            ComponentStock otherStock = otherPrice.getStockInfo();
                            String otherEncapsulation = otherPrice.getEncapsulation();

                            if (otherStock != null
                                    && currentModel.equals(otherStock.getModel())
                                    && otherEncapsulation != null
                                    && (otherEncapsulation.contains("TR") || otherEncapsulation.contains("TB"))) {

                                trTbQty = Objects.nonNull(otherPrice.getMatchingQuantity()) ? otherPrice.getMatchingQuantity() : 0;
                                break; // 找到第一个匹配的即可
                            }
                        }
                    }

                    // 根据找到的TR/TB包装记录的qty进行计算
                    if (trTbQty == null) {
                        // 未找到对应记录，使用原逻辑
                        Long numVal = Objects.isNull(num) ? 0L : num;
                        Long stockNum = price.getStock() != null ? price.getStock() : 0L;
                        matchNum = Math.min(numVal, stockNum);
                        price.setQty(Objects.isNull(num) ? null : num.intValue());
                    } else {
                        Long toNum = to.getNum();
                        if (toNum == null) {
                            // to的NUM为null时默认设为0
                            matchNum = 0L;
                            price.setQty(0);
                        } else if (toNum > trTbQty) {
                            int result = toNum.intValue() - trTbQty;
                            matchNum = result > 0 ? (long) result : 0L;
                            price.setQty(Math.max(result, 0));

                        } else {
                            // to的NUM大于TR/TB记录的qty，当前设为0
                            matchNum = 0L;
                            price.setQty(0);
                        }
                    }
                }
            } else {
                // 非VEND0005供应商，保持原逻辑
                Long numVal = Objects.isNull(num) ? 0L : num;
                Long stockNum = price.getStock() != null ? price.getStock() : 0L;
                matchNum = Math.min(numVal, stockNum);
                price.setQty(Objects.isNull(num) ? null : num.intValue());
            }

            // 处理成本价格JSON
            processCostPriceJson(price, matchNum);
            if (flag) {
                int minNum = Objects.isNull(price.getStockInfo().getMinNum()) ? 0 : price.getStockInfo().getMinNum();
                if (!Objects.isNull(price.getMatchingQuantity())) {
                    // 保存结果的变量，初始值为matchingQuantity
                    int matchingQuantity = price.getMatchingQuantity();
                    int result = matchingQuantity;

                    // 循环累加，直到matchingQuantity大于qty
                    while (matchingQuantity <= price.getQty()) {
                        // 先保存当前值作为可能的结果
                        result = matchingQuantity;
                        // 累加minNum
                        matchingQuantity += minNum;
                    }


                    price.setMatchingQuantity(result);
                    price.setQty(result);
                }
            }

            // 处理价格JSON
            processPriceJson(price, matchNum, to, stock, price.getQty());
            // 计算折扣
            price.setMatchPrice(Objects.nonNull(price.getMatchPrice()) ? price.getMatchPrice() : price.getMatchCostPrice());
            calculateDiscount(price);
        }
    }

    /**
     * 计算匹配数量
     */
    private Long calculateMatchNum(Long requestedNum, Long availableStock) {
        if (requestedNum == null || availableStock == null) {
            return 0L;
        }
        return Math.min(requestedNum, availableStock);
    }

    /**
     * 处理成本价格JSON
     */
    private void processCostPriceJson(ComponentPrice price, Long matchNum) {
        if (StrUtil.isBlank(price.getCostJson())) {
            return;
        }

        JSONArray jsonArray = JSONUtil.parseArray(price.getCostJson());
        StringBuilder priceBuilder = new StringBuilder();
        StringBuilder quantityBuilder = new StringBuilder();

        // 构建价格和数量文本
        jsonArray.forEach(item -> {
            JSONObject obj = (JSONObject) item;
            priceBuilder.append(obj.getStr("Price")).append("<br/>");
            quantityBuilder.append(obj.getStr("Quantity")).append("<br/>");
        });

        price.setCostPriceText(priceBuilder.toString());
        price.setNumText(quantityBuilder.toString());

        // 计算匹配成本价格
        if (matchNum != 0) {
            price.setMatchCostPrice(findPriceForQuantity(jsonArray, matchNum));
            price.setMatchingQuantity(Objects.nonNull(findQuantityForQuantity(jsonArray, matchNum)) ? findQuantityForQuantity(jsonArray, matchNum).intValue() : null);
        }
    }

    /**
     * 处理价格JSON
     */
    private void processPriceJson(ComponentPrice price, Long matchNum, QueryTO to, ComponentStock stock, Integer qty) {
        if (StrUtil.isBlank(price.getJson())) {
            return;
        }

        JSONArray jsonArray = JSONUtil.parseArray(price.getJson());
        StringBuilder priceBuilder = new StringBuilder();

        // 构建价格文本
        jsonArray.forEach(item -> {
            JSONObject obj = (JSONObject) item;
            priceBuilder.append(obj.getStr("Price")).append("<br/>");
        });
        price.setPriceText(priceBuilder.toString());

        // 计算匹配价格
        if (matchNum != 0) {
            boolean isDigikeyDigiReel = Objects.equals(SupplierCodeEnum.DIGIKEY.getCode(), stock.getSupplierCode()) &&
                    !StrUtil.isBlank(price.getEncapsulation()) &&
                    price.getEncapsulation().contains("Digi-Reel");

            price.setMatchPrice(isDigikeyDigiReel ?
                    findPriceForQuantityOfDigikey(jsonArray, matchNum, to.getCurrency(), Objects.nonNull(qty) ? qty.longValue() : null) :
                    findPriceForQuantity(jsonArray, matchNum));
        }
    }

    /**
     * 计算折扣
     */
    private void calculateDiscount(ComponentPrice price) {
        if (StrUtil.isBlank(price.getMatchPrice()) || StrUtil.isBlank(price.getMatchCostPrice())) {
            return;
        }
        if (Objects.nonNull(price.getStockInfo()) && Objects.equals(price.getStockInfo().getSupplierCode(), "VEND0006")) {
            price.setMatchDiscount("0.9");
            return;
        }

        try {
            BigDecimal matchPrice = new BigDecimal(price.getMatchPrice());
            BigDecimal matchCostPrice = new BigDecimal(price.getMatchCostPrice());
            BigDecimal discount = matchPrice.divide(matchCostPrice, 2, RoundingMode.HALF_UP);
            price.setMatchDiscount(discount.toPlainString());
        } catch (ArithmeticException e) {
            logger.error("计算折扣异常", e);
            price.setMatchDiscount("0.00");
        }
    }

    private CompletableFuture<List<ComponentPrice>> createAsyncTaskResult(Supplier<List<ComponentPrice>> task,
                                                                          String supplierName,
                                                                          List<String> models) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                long startTime = System.currentTimeMillis();
                List<ComponentPrice> result = task.get(); // 执行任务并获取结果
                long endTime = System.currentTimeMillis();

                long duration = endTime - startTime;
                logger.info("{}异步任务执行完成，耗时: {}ms，数据: {}",
                        supplierName, duration, models.toString());
                return result;
            } catch (Exception e) {
                logger.error("{}异步任务执行异常", supplierName, e);
                MessageUtil.sentMessage("26827",
                        "createAsyncTask【" + supplierName + "】" + e.getMessage(),
                        "createAsyncTask");
                return Collections.emptyList(); // 异常时返回空列表
            }
        }, quoteExecutor);
    }


    /**
     * 创建带异常处理的异步任务
     */
    private CompletableFuture<Void> createAsyncTask(Runnable task, String supplierName, List<String> models) {
        return CompletableFuture.runAsync(() -> {
            try {
                // 只测量task.run()的执行时间
                long startTime = System.currentTimeMillis();
                task.run();
                long endTime = System.currentTimeMillis();

                long duration = endTime - startTime;
                logger.info("{}异步任务的task.run()执行完成，耗时: {}ms，数据: {}", supplierName, duration, models.toString());
            } catch (Exception e) {
                logger.error("{}异步任务执行异常", supplierName, e);
                MessageUtil.sentMessage("26827", "createAsyncTask【" + supplierName + "】" + e.getMessage(), "createAsyncTask");
            }
        }, quoteExecutor);
    }


    public List<ComponentPrice> groupBySupplierCode(List<ComponentPrice> data, List<String> supplierCodeList) {
        // 按supplierCode分组，处理可能的null值
        Map<String, List<ComponentPrice>> groupedMap = data.stream().filter(x -> Objects.nonNull(x.getStockInfo()))
                .collect(Collectors.groupingBy(price ->
                        // 安全获取supplierCode，避免空指针
                        Optional.ofNullable(price.getStockInfo())
                                .map(ComponentStock::getSupplierCode)
                                .orElse(null)
                ));

        // 为每个分组创建父对象并设置children
        List<ComponentPrice> result = new ArrayList<>();
        for (Map.Entry<String, List<ComponentPrice>> entry : groupedMap.entrySet()) {
            String supplierCode = entry.getKey();
            List<ComponentPrice> children = entry.getValue();

            // 创建父对象
            ComponentPrice parent = new ComponentPrice();
            // 设置父对象的supplierCode（通过stockInfo关联）
            ComponentStock parentStock = new ComponentStock();
            parentStock.setSupplierCode(supplierCode);
            parent.setStockInfo(parentStock);
            // 设置子对象列表
            parent.setChildren(children);

            result.add(parent);
        }

        List<ComponentPrice> orderedResult = new ArrayList<>(result.size());
        for (String supplier : supplierCodeList) {
            // 找到对应uniqueId的ComponentPrice
            for (ComponentPrice price : result) {
                if (supplier.equals(price.getStockInfo().getSupplierCode())) {
                    orderedResult.add(price);
                    break;
                }
            }
        }
        return orderedResult;
    }
}
